import { isRejected } from "q";
import { pureCheckToken } from './cheToken';
/* eslint-disable 

import utils from '../../assets/scripts/utils'
// Vue.prototype.$utils = utils // main.js中全局引入
let id = utils.getUrlKey('id')
*/
export default {
    getUrlKey: function (name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
    },
    setCookie: function (cname, cvalue, exdays) {
        var d = new Date();
        //console.log(d);
        //d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        //单位是1秒
        d.setTime(d.getTime() + (exdays * 1000));
        //var expires = "expires=" + d.toUTCString();
        var expires = "expires=" + d.toUTCString();

        //console.info(cname + "=" + cvalue + "; " + expires);
        document.cookie = cname + "=" + cvalue + ";domain=.springbootjwt.com" + "; " + expires;
        //console.info(document.cookie);
    },
    setCookieD: function (cname, cvalue, domain, exdays) {
        var d = new Date();
        console.log(d);
        //d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        d.setTime(d.getTime() + (exdays * 1000));
        //var expires = "expires=" + d.toUTCString();
        var expires = "expires=" + d;

        console.info(cname + "=" + cvalue + "; " + expires);
        document.cookie = cname + "=" + cvalue + "; " + "domain" + "=" + domain + "; " + expires;
        //console.info(document.cookie);
    },
    //获取cookie
    getCookie: function (cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        console.log("获取cookie,现在循环")
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            //console.log(c)
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) != -1) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    },
    //清除cookie
    clearCookie: function () {
        this.setCookie("username", "", -1);
    },
    //清除cookie
    delCookie: function (name) {
        this.setCookie(name, "", -1);
    },
    //把url后面的参数去掉
    delUrlParams: function (url) {
        //如果没有？ 会返回-1
        //console.log("?????===="+url.indexOf('?'))
        if (url.indexOf('?') != -1) {
            return url.substring(0, url.indexOf('?'));
        } else {
            return url
        }

    },
    //得到url域名host
    getUrl: function (url) {
        var domain = url.split('/'); //以“/”进行分割
        if (domain[2]) {
            domain = domain[0] + '//' + domain[2];
        } else {
            domain = ''; //如果url不正确就取空
        }
    },

    //加载一个隐藏的iframe
    setIframe: function () {
        var ifr = document.createElement('iframe');
        ifr.id = "myframeId";
        ifr.src = 'http://www.sso.com';
        ifr.name = "myframeName";
        ifr.style.display = 'none';
        document.body.appendChild(ifr);
        console.log('0000000-----ifr.onload之前');

        return Promise.resolve("89889");
    },
    //添加监听器  接收SSO的消息
    addEve: function (needCretential,Vue, VueObj, comId) {
        console.log('111111-----addEve');
        let ssoflag = Vue.prototype.sssoflag = { flag: null };
        let pureCOk = Vue.prototype.pureCheckOk = { flag: null };
        //let ssoflag = {flag:null};
        let _that = this;
        //监听pureOK这个变量的变化，有变化就加载vue组件
        Object.defineProperty(pureCOk, 'flag', {
            get: function () {

            },
            set: function (newValue) {
                //收到变化 加载组件 
                VueObj.$mount(comId)
                console.log("55555挂载成功")
            }
        })
        //ssoflag有变化说明从SSO拿到消息，
        //并且token已经保存到localStorage中
        //pureCheckToken()验证token是否有效
        Object.defineProperty(ssoflag, 'flag', {
            get: function () {

            },
            set: function (newValue) {
                console.log("33333执行defineProperty")
                //需要触发的渲染函数可以写在这...
                pureCheckToken().then(data => {
                    console.log("4444444执行pureCheckToken后面")
                    if (data == "ok") {

                        console.log("data是" + data)
                        pureCOk.flag = "ok";
                        return Promise.resolve("addEvent");
                        //跑到首页
                        //window.location.href=document.location.protocol+"//"+window.location.host
                        //window.location.href = utils.delUrlParams(window.location.href);
                    } else if (data == "service_error") {
                        console.log("跳转error");
                        window.location.href = "/error"
                        //window.location.href = "http://www.sso.com/login?redirect=" + utils.delUrlParams(window.location.href);
                    } else {
                        console.log("data是" + data)
                        window.location.href = "http://www.sso.com/login?redirect=" + _that.delUrlParams(window.location.href);

                    }
                })
            }
        });
        //监听器   从sso拿token和cookie
        //监听器是异步的 所有才用上面的Object.defineProperty监听变量的变化
        window.addEventListener('message', (event) => {
            if (event.origin.includes('sso.com')) {
                console.log('接受到sso的消息');
                localStorage.setItem('token', event.data.token);
                //if (!this.getCookie('nickname')) {
                // this.setCookie('nickname', event.data.nickname, 1296000);
                //}
                let cookies = event.data.cookies;
                
                if (cookies) {
                    for (let k in cookies) {
                        //console.log(k, cookies[k]);
                        _that.setCookie(k, cookies[k], 1296000)
                    }

                }
                //伪造一些无用的cookie，
                _that.fillCookie()
                console.log("222222-addEventListener");
                if(needCretential){
                    //needCretential为true就验证token才显示组件
                   
                    ssoflag.flag = 'ok';
                }else{
                    //不要验证 直接显示组件
                    pureCOk.flag = "ok";
                }
                
                
            };

        }, true);

        //return Promise.resolve("addEvent");
    },
    //得到随机整数
    GetRandomNum(Min, Max) {
        var Range = Max - Min;
        var Rand = Math.random();
        //round +0.5  再取整
        return (Min + Math.round(Rand * Range));
    },
    //随机字符串
    randomString(len) {
        len = len || 46;
        //把t字母去掉，因为验证token时用到一个cookie,key是tRoU,
        //伪造cookie时 要避免把tRoU覆盖
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprswxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        for (let i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    },
    //伪造cookie 把cookie数量填充至30个，可以自定义数量
    fillCookie() {
        var cookieArry = document.cookie.split(";");
        var setCookNum;
        if (cookieArry.length < 30) {
            setCookNum = 30 - cookieArry.length;
        }

        console.log("cookie数---" + setCookNum)

        for (let i = 1; i <= setCookNum; i++) {
            let k = this.randomString(this.GetRandomNum(1, 6));
            let kvalue = this.randomString(this.GetRandomNum(5, 46));
            //15天 21600分钟
            this.setCookie(k, kvalue, 1296000)
        }
    }
}
